request = require 'request'
db = require './db'

city_area = []

search = (keyword, callback)->
	url = "http://www.baidu.com/s?wd=#{keyword}"
	results = []
	titleRex = /<a.+?>(.+?)<\/a>/ig
	request.get url, (err,res,body)->
		body = body.replace(/\n/g,'').replace(/\t/g,'').replace(/\r/g,'')
		matchs = body.match /<h3 class=\"t\">(.+?)<\/h3>/ig
		matchs.forEach (match)->
			result = titleRex.exec(match.replace(/\s/ig,''))
			if result?.length>0
				results.push result[1]
			else
				result = /<em>(.+?)<\/em>/ig.exec match
				results.push result[1] if result?.length>0
		callback err, results

findCity = (html)->
	city = null
	index = 1000000000
	city_area.forEach (item)->
		i = html.indexOf item.city
		if i>0 and i<index
			index = i
			city = item.city
	return city

sql = 'SELECT * FROM city_area'
db.runSql sql, (err, results)->
	city_area = results

module.exports = 
	search: search
	getCity :(companyName,callback)->
		url = "http://www.baidu.com/s?ie=utf-8&wd=#{companyName} 公司地址"
		request.get url, (err, res, body)->
			city = findCity body
			callback err,city